/**
 *author:yhb
 */
package com.towker.frame.controller.rbac;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.towker.core.util.BeanUtils;
import com.towker.frame.model.rbac.*;
import com.towker.frame.service.rbac.res.ResourceService;
import com.towker.frame.service.rbac.sys.SubsystemService;
import com.towker.frame.share.rbac.res.PermissionShare;
import com.towker.frame.share.sys.user.UserShare;
import com.towker.web.MyRequest;

@Controller
@RequestMapping("/manage/rbac/res")
public class ResourceController{
	private ResourceService service;
	private SubsystemService subsystemService;
	public void setResourceService(ResourceService service){this.service = service;}
	public void setSubsystemService(SubsystemService service){this.subsystemService=service;};
	/**添加系统资源*/
	@RequestMapping("/addResource{viewName}")
	public ModelAndView addResource(HttpServletRequest request,HttpServletResponse response, Resource resource, @PathVariable
	String viewName) throws Exception{
		ModelAndView result=null;
		MyRequest req = new MyRequest(request);
		if ("1".equals(viewName)){
			Long id = req.getLong("id");
			Resource parentResource=service.getById(id);
			Subsystem subsystem=subsystemService.getById(new Long(req.getLong("systemid")));
			result=new ModelAndView();
			if(null == parentResource)parentResource=new Resource();
			result.addObject("parentResource",parentResource);
			result.addObject("subsystem",subsystem);
			result.setViewName("/manage/rbac/res/addResource.jsp");
		}else if("2".equals(viewName)){
			PrintWriter writer=response.getWriter();
			try{
				service.addResource(resource,req.getStringValues("relatedRes"));
				PermissionShare permissionHelper=(PermissionShare)BeanUtils.getBean(PermissionShare.class);
				permissionHelper.removeSysPermissionCache(UserShare.getCurrentSystemId(request)+"");
				writer.write("系统资源添加成功！");
			}catch (Exception e){e.printStackTrace();writer.write("系统资源添加失败！");}
		}
		return result;
	}
	/**根据资源编号删除该资源并且与该资源有关的所有信息*/
	@RequestMapping("/delResource")
	public void delResource(HttpServletRequest request, HttpServletResponse response) throws Exception{
		MyRequest req = new MyRequest(request);
		Long id =new Long(req.getLong("id"));
		PrintWriter writer = response.getWriter();
		try{
			service.delResource(id);
			PermissionShare permissionHelper=(PermissionShare)BeanUtils.getBean(PermissionShare.class);
			permissionHelper.removeSysPermissionCache(UserShare.getCurrentSystemId(request)+"");
			writer.write("1");
		}catch (Exception e){
			e.printStackTrace();
			writer.write("0");
		}
	}
	/**根据系统编号删除系统下的所有资源*/
	@RequestMapping("/delResBySysid")
	public void delResBySysid(HttpServletRequest request, HttpServletResponse response) throws Exception{
		MyRequest req = new MyRequest(request);
		Long sysid = req.getLong("sysid");
		PrintWriter out = response.getWriter();
		try{
			service.delResBySysid(sysid);
			PermissionShare permissionHelper=(PermissionShare)BeanUtils.getBean(PermissionShare.class);
			permissionHelper.removeSysPermissionCache(UserShare.getCurrentSystemId(request)+"");
			out.print(1);
		}catch (Exception e){e.printStackTrace();out.print(0);}
	}
	/**修改资源*/
	@RequestMapping("/updResource{viewName}")
	public ModelAndView updResource(HttpServletRequest request, HttpServletResponse response, @PathVariable
	String viewName, Resource resource) throws IOException, Exception{
		ModelAndView result=null;
		if ("1".equals(viewName)){
			MyRequest req = new MyRequest(request);
			long id = req.getLong("id");
			Resource oldResource = service.getById(id);
			result = new ModelAndView();
			Resource parentResource=service.getById(oldResource.getParentid());
			result.addObject("parentResource",parentResource);
			result.addObject("resource", oldResource);
			if(new Long(1L).equals(oldResource.getViewandoption())){
				List<Resource> children=service.getChildrenResByIdAndSysid(id,oldResource.getSystemid());
				result.addObject("children",children);
			}
			result.setViewName("/manage/rbac/res/updResource.jsp");
		}else if("2".equals(viewName)){
			PrintWriter writer = response.getWriter();
			MyRequest req=new MyRequest(request);
			if(0L==req.getLong("isvisable"))resource.setIsvisable(0L);
			String relatedRes=req.getStringValues("relatedRes");
			Resource tmp=service.getById(resource.getId());
			resource.setSystemid(tmp.getSystemid());
			service.updateResource(resource,relatedRes);
			PermissionShare permissionHelper=(PermissionShare)BeanUtils.getBean(PermissionShare.class);
			permissionHelper.removeUserPermissionCache(UserShare.getCurrentUserId(request)+"");
			permissionHelper.removeSysPermissionCache(UserShare.getCurrentSystemId(request)+"");
			writer.write("修改系统资源成功！");
		}
		return result;
	}
	/**给资源排序*/
	@RequestMapping("/sortRes{viewName}")
	public ModelAndView sortRes(HttpServletRequest request, HttpServletResponse response, @PathVariable
	String viewName) throws Exception{
		ModelAndView result=new ModelAndView();
		MyRequest req = new MyRequest(request);
		PrintWriter out = response.getWriter();
		if("1".equals(viewName)){//子节点检查
			try{
				List<Resource> children=service.getChildrenResById(req.getLong("id"));
				if(null==children||1>=children.size()){
					out.print(-1);return null;
				}else{out.print(1);return null;}
			}catch (Exception e){e.printStackTrace();}
		}else if ("2".equals(viewName)){//根节点检查
			try{
				List<Resource> roots=service.getRootResBySysid(req.getLong("sysid"));	
				if(null==roots||1>=roots.size()){
					out.print(-1);return null;
				}else{out.print(1);return null;}
			}catch (Exception e){e.printStackTrace();}
		}else if ("3".equals(viewName)){//子节点排序
			try{
				List<Resource> children=service.getChildrenResById(req.getLong("id"));	
				result.addObject("data",children);
				result.setViewName("/manage/rbac/res/sortRes.jsp");
				return result;
			}catch (Exception e){e.printStackTrace();}
		}else if("4".equals(viewName)){//根节点排序
			try{
				List<Resource> roots=service.getRootResBySysid(req.getLong("sysid"));	
				result.addObject("data",roots);
				result.setViewName("/manage/rbac/res/sortRes.jsp");
				return result;
			}catch (Exception e){e.printStackTrace();}
		}else if("5".equals(viewName)){//排序
			try{
				service.sortResource(req.getString("resIds"));
				out.print(1);
				return null;
			}catch(Exception e){e.printStackTrace();out.print(0);return null;}
		}
		return result;
	}
	/**根据系统编号进入到相应的资源数据管理视图*/
	@RequestMapping("/getResource{viewName}")
	public ModelAndView getResource(HttpServletRequest request, HttpServletResponse response, @PathVariable
	String viewName) throws IOException{
		ModelAndView result=null;
		if ("1".equals(viewName)){
			result=new ModelAndView();
			result.setViewName("/manage/rbac/res/getResource.jsp");
		}else if("2".equals(viewName)){
			MyRequest req = new MyRequest(request);
			Long systemid = req.getLong("systemid");
			try{
				PrintWriter writer = response.getWriter();
				String tree = service.getResourceTreeBySystemid(systemid);
				writer.write(tree);
			}catch (Exception e){e.printStackTrace();}
		}
		return result;
	}
	/**获得角色的资源树*/
	@RequestMapping(value = "/getResourceTreeOfRole")
	public void getResourceTreeOfRole(HttpServletRequest request, HttpServletResponse response) throws IOException{
		MyRequest req = new MyRequest(request);
		long sysid = req.getLong("sysid");
		long roleid = req.getLong("roleids");
		PrintWriter writer = response.getWriter();
		String str = service.getResourceTreeOfRole(sysid, roleid);
		writer.write(str);
	}
	/**获得用户资源树
	 * @throws IOException*/
	@RequestMapping("/getUserResTree")
	public void getUserResTree(HttpServletRequest request, HttpServletResponse response) throws IOException{
		MyRequest req = new MyRequest(request);
		long userid = req.getLong("userid");
		long sysid = req.getLong("sysid");
		String tree =service.getUserResJson(userid,sysid,1);
		PrintWriter writer = response.getWriter();
		writer.write(tree);
	}
	/**创建与资源相对应的权限标签*/
	@RequestMapping(value = "/newTag")
	public ModelAndView newTag(HttpServletRequest request, HttpServletResponse response) throws Exception{
		MyRequest req = new MyRequest(request);
		Long id = req.getLong("id");
		Resource res = null;
		try{
			res = service.getById(id);
		}catch (Exception e){e.printStackTrace();}
		ModelAndView result = new ModelAndView();
		result.addObject("res", res);
		result.setViewName("/manage/rbac/res/newTag.jsp");
		return result;
	}
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getIcon")
	public void getIcon(HttpServletResponse response) throws IOException{
		PrintWriter writer=response.getWriter();
		//C:\Program Files\apache-tomcat-6.0.20\webapps\baseframework
		String fPath=this.getClass().getResource("").getPath();
		String tmp=fPath;
		///C:/Program%20Files/apache-tomcat-6.0.20/webapps/baseframework/WEB-INF/classes/com/towker/frame/controller/rbac/
		tmp=tmp.substring(1);
		tmp=tmp.substring(0,tmp.indexOf("/WEB-INF"));
		tmp=tmp+"/icon";
		tmp=tmp.replace("%20", " ");
		List list=service.getIconList(tmp);
		String str=list+"";
		writer.write(str.replace("[","").replace("]","").replace(" ","").replace("\\", "/").replace("/web",""));
	}
}
